package com.cat.model.biz.service.admin.impl;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alonew.core.commons.tuple.TwoTuple;
import com.alonew.db.dao.TxCommonDAO;
import com.cat.model.biz.service.admin.AlbumService;
import com.cat.model.common.model.common.AlbumModelVO;
import com.cat.model.common.model.common.AlbumVO;
import com.cat.model.common.util.FileUtil;
import com.cat.model.common.util.StaticFileUtil;

@Service("AlbumService")
public class AlbumServiceImpl implements AlbumService{
	@Autowired
	private TxCommonDAO commonDAO;
	
	@Override
	public AlbumVO createAlbum(AlbumVO album, File coverImage,
			String coverImageFileName){
		if(coverImage != null){
			String imagePath = StaticFileUtil.albumRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(coverImage);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, coverImageFileName, md5AndData.second);
			album.setCoverImage(imagePath + "/" + coverImageFileName);
		}
		
		commonDAO.insert(album);
		
		return album;
	}
	
	@Override
	public int deleteAlbum(long id){
		AlbumVO album = new AlbumVO();
		album.setId(id);
		return commonDAO.deleteById(album);
	}
	
	@Override
	public int updateAlbum(AlbumVO album, File coverImage,
			String coverImageFileName){
		if(coverImage != null){
			String imagePath = StaticFileUtil.albumRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(coverImage);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, coverImageFileName, md5AndData.second);
			album.setCoverImage(imagePath + "/" + coverImageFileName);
		}
		
		return commonDAO.updateById(album, "name", "coverImage","description");
	}
	
	@Override
	public AlbumModelVO createAlbumModel(AlbumModelVO albumModel){
		
		commonDAO.insert(albumModel);
		
		return albumModel;
	}
	
	@Override
	public int deleteAlbumModel(long id){
		AlbumModelVO albumModel = new AlbumModelVO();
		albumModel.setId(id);
		return commonDAO.deleteById(albumModel);
	}
	
	@Override
	public int updateAlbumModel(AlbumModelVO albumModel){
		
		return commonDAO.updateById(albumModel, "modelId", "type");
	}
}
